package com.foxconn.ipebg.common.system.controller;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.entity.Org;
import ipebg.mzk.facade.entity.OrgLevel;
import ipebg.mzk.facade.system.bean.OrgBean;
import ipebg.mzk.facade.system.bean.OrgTreeBean;
import ipebg.mzk.facade.system.service.OrgLevelService;
import ipebg.mzk.facade.system.service.OrgService;
import ipebg.mzk.facade.system.service.UserService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 組織信息——組織代碼維護
 * @author H2601982楊小雲
 *
 */

@Controller
@RequestMapping("/org.do")
public class OrgController {
	@Resource(name = "userServiceImpl")
	private UserService userServiceImpl;
	
	@Resource(name = "orgServiceImpl")
	private OrgService orgService;
	
	@Resource(name="orgLevelImpl")
	private OrgLevelService orgLevelService;

	@RequestMapping(params="action=loadOrgPage")
	public String loadOrgPage() {
		return "pages/common/system/org";
	}
	
	/**
	 * 組織信息列表界面
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params="action=orgList")
	public void orgList(Model model, HttpServletRequest request, HttpServletResponse response) {
		String orgCode = request.getParameter("f_orgCode");
		String orgName = request.getParameter("f_orgName");
		String enable = request.getParameter("f_enable");
		OrgBean bean = new OrgBean();
		bean.setOrgCode(orgCode);
		bean.setOrgName(orgName);
		bean.setEnable(enable);
		
		String page = request.getParameter("page");
		String length = request.getParameter("rows");
		int iPageIndex = 1;
		int ilength = 10;
		if (page != null && page != "") {
			iPageIndex = Integer.parseInt(page);
		}
		if (length != null && length != "") {
			ilength = Integer.parseInt(length);
		}
		try{
			Page initiontpage = orgService.getAllList(bean, iPageIndex, ilength);
			List<Org> list = (List<Org>) initiontpage.getResult();
			List<OrgBean> beanList = orgService.toBean(list);
			model.addAttribute("rows", beanList);
			model.addAttribute("total", initiontpage.getTotalCount());
			response.getWriter().write(JSON.toJSONString(model));//?
		}catch (Exception e) {
			e.printStackTrace();
		}
		//return "common/base/org";
	}
	
	/**
	 * 獲取組織層架——新增修改頁面賦初始值
	 */
	@RequestMapping(params="action=getOrgLevelList")
	public void getOrgLevelList(Model model, HttpServletRequest request, HttpServletResponse response) {
		List<OrgLevel> orgLevelList = orgService.getOrgLevelList();
		model.addAttribute("orgLevelList", orgLevelList);
		try {
			response.getWriter().write(JSON.toJSONString(model));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通過工號獲取主管姓名
	 */
	@RequestMapping(params="action=getAdminUserName")
	public void getAdminUserName(Model model, HttpServletRequest request, HttpServletResponse response) {
		String leaderNo = request.getParameter("leaderNo"); 
		MsAdminUser user = userServiceImpl.getEnableUserByName(leaderNo);
		if(user!=null) {
			model.addAttribute("result", "success");
			model.addAttribute("leaderName", user.getRealName());
		} else {
			model.addAttribute("result", "failure");
		}
		try {
			response.getWriter().write(JSON.toJSONString(model));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 新增
	 */
	@RequestMapping(params="action=addOrg")
	public void addOrg(Model model, HttpServletRequest request, HttpServletResponse response) {
		//String orgId = request.getParameter("orgId");
		String currentUserCode = SecurityContextHolder.getContext().getAuthentication().getName();//獲取當前登錄人的工號
		String dominate = request.getParameter("dominate");
		String orgName = request.getParameter("orgName");
		String orgCode = request.getParameter("orgCode");
		String orgFee = request.getParameter("orgFee");
		String levelId = request.getParameter("levelId");
		String leaderNo = request.getParameter("leaderNo");
		String leaderName = request.getParameter("leaderName");
		String parentId = request.getParameter("parentId");
		String enable = request.getParameter("enable");
		
		Org orgExist = orgService.findByCode(orgCode);
		Org orgParent = orgService.findById(parentId);
		OrgLevel orgLevel = orgService.findOrgLevelById(levelId);
		//OrgLevel orgLevelParent = orgService.findOrgLevelById(orgParent.getLevelId());
		if(orgExist!=null) {
			model.addAttribute("result", "exist");
		} else if(orgParent!=null && orgLevel.getLevelNumber()>=orgService.findOrgLevelById(orgParent.getLevelId()).getLevelNumber()) {
			model.addAttribute("result", "highLevel");
		} else {
			Org entity = new Org();
	   		Date date = new Date(); 
	   		entity.setDominate(dominate);
	   		entity.setOrgCode(orgCode);
	   		entity.setOrgName(orgName);
	   		entity.setOrgFee(orgFee);
	   		entity.setLevelId(levelId);
	   		entity.setLeaderNo(leaderNo);
	   		entity.setLeaderName(leaderName);
	   		entity.setParentId(parentId);
	   		entity.setEnable(enable);
	   		entity.setCreateName(currentUserCode);
	   		entity.setCreateTime(date);
	   		entity.setModifyTime(date);
	   		if(orgService.saveOrUpdateOrg(entity)) {
	   			model.addAttribute("result", "success");
	   		} else {
	   			model.addAttribute("result", "failure");
	   		}
		}
   		
		try {
			response.getWriter().write(JSON.toJSONString(model));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(params="action=editOrg")
	public void editOrg(Model model, HttpServletRequest request, HttpServletResponse response) {
		String orgId = request.getParameter("orgId");
		String currentUserCode = SecurityContextHolder.getContext().getAuthentication().getName();//獲取當前登錄人的工號
		String dominate = request.getParameter("dominate");
		String orgName = request.getParameter("orgName");
		String orgCode = request.getParameter("orgCode");
		String orgFee = request.getParameter("orgFee");
		String levelId = request.getParameter("levelId");
		String leaderNo = request.getParameter("leaderNo");
		String leaderName = request.getParameter("leaderName");
		String parentId = request.getParameter("parentId");
		String enable = request.getParameter("enable");
		
		Org orgExist = orgService.findByCode(orgCode);
		Org orgParent = orgService.findById(parentId);
		OrgLevel orgLevel = orgService.findOrgLevelById(levelId);
		//OrgLevel orgLevelParent = orgService.findOrgLevelById(orgParent.getLevelId());
		if(orgExist!=null && !orgExist.getOrgId().equals(orgId)) {
			//組織代碼唯一性校驗
			model.addAttribute("result", "exist");
		} else if(orgParent!=null && orgLevel.getLevelNumber()>=orgService.findOrgLevelById(orgParent.getLevelId()).getLevelNumber()) {
			//當前層級不能高於或等於上級組織層級
			model.addAttribute("result", "highLevel");
		} else {
			Org entity = orgService.findById(orgId);
	   		Date date = new Date(); 
	   		entity.setDominate(dominate);
	   		entity.setOrgCode(orgCode);
	   		entity.setOrgName(orgName);
	   		entity.setOrgFee(orgFee);
	   		entity.setLevelId(levelId);
	   		entity.setLeaderNo(leaderNo);
	   		entity.setLeaderName(leaderName);
	   		entity.setParentId(parentId);
	   		entity.setEnable(enable);
	   		entity.setModifyName(currentUserCode);
	   		entity.setModifyTime(date);
	   		if(orgService.saveOrUpdateOrg(entity)) {
	   			model.addAttribute("result", "success");
	   		} else {
	   			model.addAttribute("result", "failure");
	   		}
		}
		
   		
		try {
			response.getWriter().write(JSON.toJSONString(model));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 刪除
	 */
	@RequestMapping(params="action=delOrg")
	public void delOrg(Model model, HttpServletRequest request, HttpServletResponse response) {
		String orgId = request.getParameter("orgId");
		//此處需增加該組織代碼是否使用的邏輯處理
		
		if(orgService.delOrg(orgId)) {
			model.addAttribute("result", "success");
   		} else {
   			model.addAttribute("result", "failure");
   		}
		try {
			response.getWriter().write(JSON.toJSONString(model));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 組織信息樹形瀏覽
	 */
	@RequestMapping(params="action=orgScanTree")
	public void orgScanTree(Model model, HttpServletRequest request, HttpServletResponse response) {
		try{
			List<Org> list = orgService.getAllList();
			List<OrgTreeBean> treeList = new ArrayList<OrgTreeBean>();  
			for(Org entity:list) {
				if(entity.getEnable().equals("1")) {
					if(entity.getParentId()==null || entity.getParentId().equals("")) {
						//僅抓取有效且上級組織為空的實體
						List<OrgTreeBean> children = orgService.getOrgTreeList(entity.getOrgId());
						OrgTreeBean bean = new OrgTreeBean();
						bean.setId(entity.getOrgId());
						bean.setText(entity.getOrgName() + "(" + entity.getOrgCode() + ")");
						bean.setChecked(false);
						bean.setChildren(children);
						treeList.add(bean);
					}
				}
			}
			model.addAttribute("data", treeList);
			response.getWriter().write(JSON.toJSONString(model));//?
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 導出組織信息
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "action=export")
	public void export(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String orgCode = request.getParameter("orgCode");// 組織代碼
		String orgName = request.getParameter("orgName");// 組織名稱
		String enable = request.getParameter("enable");// 是否有效
		Org org = new Org();
		org.setOrgCode(orgCode);
		org.setOrgName(orgName);
		org.setEnable(enable);
		
		try{
			List<Org> orgList = orgService.getExcelReporterList(org);
			List<OrgBean> orgBeanList = orgService.toBean(orgList);
			
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHddss");
			String fileName = df.format(new Date());
			// 填充数据
			List<Map<String, Object>> list = createExcelRecord(orgBeanList);
			
			String columnNames[] = { "序號", "廠區", "組織代碼", "組織名稱", "費用代碼", "組織層級", "主管工號", "主管姓名","是否有效","上級組織代碼","上級組織名稱","創建人","創建時間" };// 列名
			String keys[] = { "id", "dominate", "orgCode", "orgName", "orgFee", "levelName", "leaderNo", "leaderName", "enable", "parentCode", "parentName", "createName", "createTime" };// map中的key
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			/*try {
				ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "UTF-8"));
			ServletOutputStream out = response.getOutputStream();
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(is);
				bos = new BufferedOutputStream(out);
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				throw e;
			} finally {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<Map<String, Object>> createExcelRecord(List<OrgBean> orgBeanList) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "組織信息");
		listmap.add(map);
		OrgBean bean = null;
		for (int i = 0; i < orgBeanList.size(); i++) {
			bean = orgBeanList.get(i);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			
			mapValue.put("id", i+1);//序號
			//廠區
    		if(bean.getDominate() == "ZZK" || bean.getDominate().equals("ZZK")){
    			mapValue.put("dominate","鄭州綜保區");
    		}else if(bean.getDominate() == "ZZC" || bean.getDominate().equals("ZZC")){
    			mapValue.put("dominate","鄭州加工區");
    		}else if(bean.getDominate() == "JYX" || bean.getDominate().equals("JYX")){
    			mapValue.put("dominate","濟源廠區");
    		}else if(bean.getDominate() == "JCX" || bean.getDominate().equals("JCX")){
    			mapValue.put("dominate","晉城廠區");
    		}else if(bean.getDominate() == "LHX" || bean.getDominate().equals("LHX")){
    			mapValue.put("dominate","龍華廠區");
    		}else if(bean.getDominate() == "GLX" || bean.getDominate().equals("GLX")){
    			mapValue.put("dominate","觀瀾廠區");
    		}else if(bean.getDominate() == "HBX" || bean.getDominate().equals("HBX")){
    			mapValue.put("dominate","鶴壁廠區");
    		}else if(bean.getDominate() == "NH" || bean.getDominate().equals("NH")){
				mapValue.put("dominate","內湖");
			}
    		
			mapValue.put("orgCode", bean.getOrgCode());//組織代碼
			mapValue.put("orgName", bean.getOrgName());//組織名稱
			mapValue.put("orgFee", bean.getOrgFee());//費用代碼
			mapValue.put("levelName", bean.getLevelName());//組織層級
			mapValue.put("leaderNo", bean.getLeaderNo());//主管工號
			mapValue.put("leaderName", bean.getLeaderName());//主管姓名
			//是否有效
    		if(bean.getEnable() == "0" || bean.getEnable().equals("0")){
    			mapValue.put("enable","無效");
    		}else if(bean.getEnable() == "1" || bean.getEnable().equals("1")){
    			mapValue.put("enable","有效");
    		}
			mapValue.put("parentCode", bean.getParentCode());//上級組織代碼
			mapValue.put("parentName", bean.getParentName());//上級組織名稱
    		mapValue.put("createName",bean.getCreateName());//創建人
    		mapValue.put("createTime",bean.getCreateTime());//創建時間
			
			listmap.add(mapValue);
		}
		return listmap;
	}
	
	/**
	 * 下載Excel功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=download")
	public void download(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		try{
			byte[] buff = new byte[2048];
			File file = new File(request.getSession().getServletContext().getRealPath("template/org.xlsx"));
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(("org.xlsx").getBytes(), "UTF-8"));
			long fileLength = file.length();
			String length = String.valueOf(fileLength);
			response.setHeader("Content_Length", length);
			FileInputStream in = null;
			ServletOutputStream out = null;
			try {
				in = new FileInputStream(file);
				out = response.getOutputStream();
				int bytesRead;
				while ((bytesRead = in.read(buff)) != -1) {
					out.write(buff, 0, bytesRead);
				}
			}catch (final IOException e) {
				throw e;
			} finally {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 導入組織信息
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "action=importext")
	public void importExcel(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletResponse response) {
		
		/*int tocalCount = 0;// 總數
		int failCount = 0;// 失敗數
		int successCount = 0;// 成功數
		
		String[] dominateArray = { "ZZK", "ZZC", "JYX", "JCX", "LHX", "GLX", "HBX" };
		int[] enableArray = { 0, 1 };
		String result = "";
		
		String ext = request.getParameter("ext");// 后缀名
		if(ext == ".xls" || ext.equals(".xls") || ext == ".xlsx" || ext.equals(".xlsx")){
			try {
				InputStream inputStream = file.getInputStream();
				ImportExecl poi = new ImportExecl();
				List<List<String>> list = poi.read(inputStream, ext.equals(".xls"));
				if (list != null) {
					for (int i = 1; i < list.size(); i++) {// 不读取第一行

						tocalCount++;
						//獲取數據
						List<String> cellList = list.get(i);
						String dominate = cellList.get(1);//廠區代碼:鄭州綜保區：ZZK、鄭州加工區：ZZC、濟源：JYX、晉城：JCX、龍華：LHX、觀瀾：GLX、鶴壁：HBX
						String orgCode = cellList.get(2);//組織代碼
						String orgName = cellList.get(3);//組織名稱
						String orgFee = cellList.get(4);//費用代碼
						String levelName = cellList.get(5);//組織層級
						String leaderNo = cellList.get(6);//主管工號
						String leaderName = cellList.get(7);//主管姓名
						int enable = 0;
						if(cellList.get(8).equals("")){
							failCount++;
							result += "|"+String.valueOf(i)+"&data";
							continue;
						}else{
							enable = Double.valueOf(cellList.get(8)).intValue();//是否有效，0：無效，1：有效
							Arrays.sort(enableArray); 
							if(Arrays.binarySearch(enableArray,enable) < 0){
								failCount++;
								result += "|"+String.valueOf(i)+"&data";
								continue;
							}
						}
						String parentCode = cellList.get(9);//上級組織代碼
						//String parentName = cellList.get(10);//上級組織名稱
						String createName = SecurityContextHolder.getContext().getAuthentication().getName(); 
						
						//驗證數據
						if(orgCode.equals("")){
							failCount++;
							result += "|"+String.valueOf(i)+"&data";
							continue;
						}else if(orgService.findByCode(orgCode) != null){
							result += "|"+String.valueOf(i)+"&code";
							failCount++;
							continue;
						}
						
						if(dominate.equals("")){
							failCount++;
							result += "|"+String.valueOf(i)+"&data";
							continue;
						}else{
							List<String> tempList = Arrays.asList(dominateArray);
							if(!tempList.contains(dominate)){
								failCount++;
								result += "|"+String.valueOf(i)+"&data";
								continue;
							}
						}
						
						List<OrgLevel> orgLevelList = orgService.getOrgLevelList(levelName);
						if(levelName.equals("")){
							failCount++;
							result += "|"+String.valueOf(i)+"&data";
							continue;
						}else if(orgLevelList == null || orgLevelList.equals(null)){
							failCount++;
							result += "|"+String.valueOf(i)+"&caption";
							continue;
						}

						Org org = new Org();
						org.setDominate(dominate);
						org.setOrgCode(orgCode);
						org.setOrgName(orgName);
						org.setOrgFee(orgFee);
						org.setLevelId(orgLevelList.get(0).getLevelId());//層級資料
						org.setLeaderNo(leaderNo);
						org.setLeaderName(leaderName);
						if(parentCode == null || parentCode.equals("")){
							org.setParentId("");//上級組織
						} else {
							Org orgParent = orgService.findByCode(parentCode);
							if (orgParent == null || orgParent.equals(null)) {
									failCount++;
									result += "|"+String.valueOf(i)+"&caption";
									continue;
							} else {
								org.setParentId(orgParent.getOrgCode());//上級組織
							}
						}
						org.setEnable(String.valueOf(enable));
						org.setCreateName(createName);
						org.setCreateTime(new Date());
						org.setModifyTime(new Date());
						
						orgService.saveOrUpdateOrg(org);
						successCount++;
					}
				}
				result += "|"+String.valueOf(tocalCount)+"|"+String.valueOf(successCount)+"|"+String.valueOf(failCount);
				inputStream.close();
				response.getWriter().write(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			result = "formaterror";
		}*/
		
	}
	
	/**
	 * 得到產品處的列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=getEnabledOrgBU")
	public void getEnabledOrgBU(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String levelNumber = request.getParameter("levelNumber");
			List<Org> list = orgService.findEnableOrgByLevelNum(Integer.valueOf(levelNumber));
			List<Org> list2 = new ArrayList<Org>();
			Org o = new Org();
			o.setOrgCode("");
			o.setOrgName("請選擇");
			list2.add(o);
			for(Org oo:list) {
				list2.add(oo);
			}
			response.getWriter().write(JSON.toJSONString(list2));//?
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到產品處的孩子列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=getEnabledOrgBUChildren")
	public void getEnabledOrgBUChildren(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String orgCode = request.getParameter("orgCode");
			String levelNumber = request.getParameter("levelNumber");
			Org o = orgService.findByCode(orgCode);
			List<Org> list2 = new ArrayList<Org>();
			if(o!=null) {
				List<Org> list = orgService.findChildrenByParentId(o.getOrgId(),Integer.valueOf(levelNumber));
				Org o1 = new Org();
				o1.setOrgCode("");
				o1.setOrgName("請選擇");
				list2.add(o1);
				for(Org oo:list) {
					list2.add(oo);
				}
			}
			response.getWriter().write(JSON.toJSONString(list2));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到當前登陸人的廠區及組織信息
	 */
	@RequestMapping(params = "action=getUserOrg")
	public void getUserOrg(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			StringBuffer xmlDoc = new StringBuffer();
			String currentUserCode = SecurityContextHolder.getContext().getAuthentication().getName();
			MsAdminUser currentUser = userServiceImpl.findUserByEmpNo(currentUserCode);
			xmlDoc.append(currentUser.getDominate() + ";");
			Org org=null ,madept=null,maMdept=null,prodept=null;
			org = orgService.findById(currentUser.getOrgId());
			if(org!=null && orgLevelService.findOrgLevelById(org.getLevelId()).getLevelNumber()==1) {
				xmlDoc.append(org.getOrgCode() + "&" + org.getOrgName() + ";");
				if(org.getParentId()!=null && !org.getParentId().toString().equals("")) {
					madept = orgService.findById(org.getParentId());
					if(madept!=null && orgLevelService.findOrgLevelById(madept.getLevelId()).getLevelNumber()==2) {
						xmlDoc.append(madept.getOrgCode() + "&" + madept.getOrgName() + ";");
						if(madept.getParentId()!=null && !madept.getParentId().toString().equals("")) {
							maMdept = orgService.findById(madept.getParentId());
							if(maMdept!=null && orgLevelService.findOrgLevelById(maMdept.getLevelId()).getLevelNumber()==3) {
								xmlDoc.append(maMdept.getOrgCode() + "&" + maMdept.getOrgName() + ";");
								if(maMdept.getParentId()!=null && !maMdept.getParentId().toString().equals("")) { 
									prodept = orgService.findById(maMdept.getParentId());
									if(prodept!=null && orgLevelService.findOrgLevelById(prodept.getLevelId()).getLevelNumber()==5) {
										xmlDoc.append(prodept.getOrgCode() + "&" + prodept.getOrgName() + ";");
									}
								}
								
							}
						}
						
					}
				}
				
			}
			String rtnXml = xmlDoc.toString();
			response.setContentType("text/xml");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(rtnXml);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
